package com.ruike.alisurface.ui.settings;

import android.annotation.SuppressLint;
import android.hardware.usb.UsbDevice;
import android.os.Handler;
import android.os.Message;
import android.view.TextureView;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.lgh.uvccamera.UVCCameraProxy;
import com.lgh.uvccamera.bean.PicturePath;
import com.lgh.uvccamera.callback.ConnectCallback;
import com.lgh.uvccamera.callback.PhotographCallback;
import com.lgh.uvccamera.callback.PictureCallback;
import com.lgh.uvccamera.callback.PreviewCallback;
import com.ruike.alisurface.Constant;
import com.ruike.alisurface.R;
import com.ruike.alisurface.base.BaseAty;
import com.ruike.alisurface.serialport.Ttys3Utils;
import com.ruike.alisurface.utils.ShareKey;
import com.voodoo.lib_logcat.L;
import com.voodoo.lib_utils.SharedUtils;
import com.voodoo.lib_utils.imageLoader.GlideImageLoader;

import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;

/**
 * usb 摄像头 检测页
 */
public class UsbPhoto_Aty extends BaseAty {
    @BindView(R.id.radio_mProductIds)
    RadioGroup radioMProductIdS;
    @BindView(R.id.radio_mProductId1)
    RadioButton radioMProductId1;
    @BindView(R.id.radio_mProductId2)
    RadioButton radioMProductId2;
    @BindView(R.id.img_photo)
    ImageView imgPhoto;
    @BindView(R.id.bt_op0en)
    Button btOp0en;
    @BindView(R.id.bt_close)
    Button btClose;
    @BindView(R.id.bt_take)
    Button btTake;
    @BindView(R.id.baseSetting_goback_imgv)
    ImageView goback;
    @BindView(R.id.tv_layout)
    LinearLayout tv_layout;
    TextureView textureview;


    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0xAA) {

            } else if (msg.what == 0xAB) {

            } else if (msg.what == 0xAC) {

            } else if (msg.what == 0xBB) {
//                BlApiHttp.setCameraversion(UsbPhotoActivity.this, mProductId);
                imgPhoto.setImageBitmap(null);
                GlideImageLoader.getInstance().loadImage(UsbPhoto_Aty.this, msg.obj.toString(), imgPhoto, true);
            }
        }
    };


    @Override
    protected int getLayoutResId() {
        return R.layout.app_usb_testphoto;
    }


    @Override
    protected void initViews() {
        initTitleBar(false);
        L.i("tjf-onStart-开灯");
//        initUVCCamera(12342);
        Constant.isShopShipment = true;
        Ttys3Utils.getInstance().ledOpenOrClose(0, 1, true, 15, 15);
        goback.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

    @Override
    protected void initData() {
        goback.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        String USB_ProductId = SharedUtils.getInstance().getString(ShareKey.USB_ProductId, "12342"); // 启用 支付宝刷脸支付
        if (USB_ProductId.equals("12342")) {
            radioMProductId1.setChecked(true);
        } else {
            radioMProductId2.setChecked(true);
        }

        btOp0en.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mUVCCamera != null) {
                    L.i("tjf-usb-", "==关闭连接 == ");
                    tv_layout.removeAllViews();
                    mUVCCamera.closeCamera();
//                    ImageLoader.clearImage(UsbPhotoActivity.this, imgPhoto);
                    imgPhoto.setImageBitmap(null);
                }
                if (radioMProductId1.isChecked()) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            initUVCCamera(12342);
                        }
                    });

                }
                if (radioMProductId2.isChecked()) {

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            initUVCCamera(12936);
                        }
                    });
                }

            }
        });

        btTake.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mUVCCamera != null) {
                    mUVCCamera.takePicture("test.jpg");
                } else {
                    initUVCCamera(12342);
                }
            }
        });
    }

    private UVCCameraProxy mUVCCamera;

    /**
     * 初始化UVC摄像头配置及操作
     */

    String mProductId;

    private void initUVCCamera(int ProductId) {
        L.i("tjf-usb-", "开始初始化配置 == " + ProductId);
        mProductId = String.valueOf(ProductId);
        mUVCCamera = new UVCCameraProxy(UsbPhoto_Aty.this);
        // 已有默认配置，不需要可以不设置
        mUVCCamera.getConfig()
                .isDebug(true)
                .setPicturePath(PicturePath.SDCARD)
                .setDirName("/Images/")
                /* .setProductId(14371)
                 .setVendorId(1528);*/
                .setProductId(ProductId)
                .setVendorId(3034);

//        mVendorId=3034,mProductId=12342  根据USB摄像头来区分 mVendorId供应商id   mProductId 产品id   ProductId(12936)  日期1020

        textureview = new TextureView(this);

        tv_layout.addView(textureview);
        mUVCCamera.setPreviewTexture(textureview);


        mUVCCamera.setConnectCallback(new ConnectCallback() {
            @Override
            public void onAttached(UsbDevice usbDevice) {
                mUVCCamera.requestPermission(usbDevice);
                L.i("tjf-usb-", "请求连接 ");
            }

            @Override
            public void onGranted(UsbDevice usbDevice, boolean granted) {
                if (granted) {
                    mUVCCamera.connectDevice(usbDevice);
                    L.i("tjf-usb-", "连接 ");
                } else {
                    L.i("tjf-usb-", "请求连接 ");
                    mUVCCamera.requestPermission(usbDevice);
                }
            }

            @Override
            public void onConnected(UsbDevice usbDevice) {
                L.i("tjf-usb-", "打开 ");
                mUVCCamera.openCamera();
            }

            @Override
            public void onCameraOpened() {
                L.i("tjf-usb-", "打开成功并设置预览及开始");
//                showAllPreviewSizes();
//                mUVCCamera.setPreviewSize(1280, 720);
//                mUVCCamera.setPreviewSize(1920, 1080);
                mUVCCamera.setPreviewSize(1600, 1200);
                mUVCCamera.startPreview();
            }

            @Override
            public void onDetached(UsbDevice usbDevice) {
                L.i("tjf-usb-", "关闭连接");
                mUVCCamera.closeCamera();
            }
        });

        mUVCCamera.setPhotographCallback(new PhotographCallback() {
            @Override
            public void onPhotographClick() {
//                mUVCCamera.takePicture();
//                mUVCCamera.takePicture("test.jpg");
            }
        });

        mUVCCamera.setPreviewCallback(new PreviewCallback() {
            @Override
            public void onPreviewFrame(byte[] yuv) {

            }
        });

        mUVCCamera.setPictureTakenCallback(new PictureCallback() {
            @Override
            public void onPictureTaken(final String path) {
                L.i("tjf-222-" + path);
                cancalimgTimer();
                Message msg = Message.obtain();
                msg.what = 0xBB;
                msg.obj = path;
                handler.sendMessage(msg);
            }
        });
    }


    Timer imgtime = new Timer();

    public void imgTimer() {
        imgtime.schedule(new TimerTask() {
            @Override
            public void run() {
                handler.sendEmptyMessage(0xAC);
            }
        }, 6000);
    }

    public void cancalimgTimer() {
        if (imgtime != null) {
            imgtime.cancel();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        L.i("tjf-onStop-关闭灯");
        if (mUVCCamera != null) {
            mUVCCamera.closeDevice();
            mUVCCamera.clearCache();
        }
        handler.removeCallbacksAndMessages(null);
        handler = null;
        Ttys3Utils.getInstance().ledOpenOrClose(0, 1, false, 15, 15);
        Constant.isShopShipment = false;
    }
}
